package io.gitee.chearnee.fw.openapi.filter;

import io.gitee.chearnee.fw.openapi.annotation.OpenApiAuth;
import io.gitee.chearnee.fw.openapi.processor.PreProcessor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * @author cn
 * @version 1.0
 * @description
 * @date 2021/9/22 15:45
 */
@Component
@AllArgsConstructor
public class OpenApiInterHandler implements HandlerInterceptor {

  private final PreProcessor preProcessor;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws Exception {
    OpenApiHttpServletRequestWrapped openapirequest = null;
    if (!(request instanceof OpenApiHttpServletRequestWrapped)) {
      openapirequest = new OpenApiHttpServletRequestWrapped(request);
    } else {
      openapirequest = (OpenApiHttpServletRequestWrapped) request;
    }

    if (handler instanceof HandlerMethod handlerMethod) {
        OpenApiAuth authHeader = handlerMethod.getMethodAnnotation(OpenApiAuth.class);
      if (authHeader == null) {
        authHeader = handlerMethod.getBeanType().getAnnotation(OpenApiAuth.class);
      }
      if (authHeader != null && authHeader.ignoreAuth()) {
        return HandlerInterceptor.super.preHandle(openapirequest, response, handler);
      }
    }
    preProcessor.checkHeaders(openapirequest);
    preProcessor.checkRepeatRequest(openapirequest);
    preProcessor.expiredRequest(openapirequest);
    preProcessor.checkSignature(openapirequest);
    if (Boolean.TRUE.equals(preProcessor.preAccessTokenHandler(handler))) {
      preProcessor.checkAccessToken(openapirequest);
    }
    //preProcessor.initContext(openapirequest);
    return HandlerInterceptor.super.preHandle(openapirequest, response, handler);
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) throws Exception {
    HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
      Object handler, Exception ex) throws Exception {
    // preProcessor.disposeContext();
    HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
  }
}
